package convertorController;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
//import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import myPDFParagraph.myParagraph;

//import org.apache.commons.fileupload.FileItem;
//import org.apache.commons.fileupload.FileUploadException;
//import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.foxit.pdf.dao.PDF2PDF;

import generateXML.XmlGenerator;
import generateXML.XmlParse;

@Controller
public class convertController {
	
	protected static final Logger logger = Logger.getLogger(convertController.class);
	
	public String strSrcPath = "";
	public String strCurrFileName = "";
	public int nPdfCount = 0;
	public int nCurrPage = 0;
	public int nCurrParaGraph = 0;
	
	public int getPdfCount() {
		if ("".equals(this.strSrcPath)) {
			return 0;
		}
		
		File file = new File(this.strSrcPath);
		File[] filelist = file.listFiles();
        for (File f : filelist){
        	this.nPdfCount = 0;
        	System.out.print(f.getName());
        	String strFileName = f.getName();
        	int length = strFileName.length();
        	//判断是否是pdf文件
        	if (".pdf".equals(strFileName.substring(length - 4, length))) {				
				this.nPdfCount ++;
			}
        }
		return this.nPdfCount;
	}
	
	//private String strCurrFileName = "";

	@RequestMapping(value = "/getPath.do")
	public void getPath(HttpServletRequest request, HttpServletResponse response) throws IOException{
		File file = new File(request.getParameter("filePath"));
		if (!file.isDirectory()) {
			System.out.println("is not a derectory!");
			return;
		}else {
			this.strSrcPath = request.getParameter("filePath");
		}
	}
	
	@RequestMapping(value = "/generate.do")
	public void generate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		deleteSubDirectory(this.strSrcPath);
		
		File file = new File(this.strSrcPath);
		File[] filelist = file.listFiles();
		
		logger.debug("generateXml Begin!!!********************");
		
        for (File f : filelist){
        	this.strCurrFileName = f.getName();
        	int length = this.strCurrFileName.length();
        	//判断是否是pdf文件
        	if (".pdf".equals(this.strCurrFileName.substring(length - 4, length))) {
        		
        		logger.debug("CurrPDFPile: " + strCurrFileName);
        		
        		String strFilepathString = strSrcPath + "/" + this.strCurrFileName;
				long lMgr = PDF2PDF.FP2PCreateModuleMgr();
				long lNewProcessor = PDF2PDF.FP2PNewProcessor();
				int nStartExtract = PDF2PDF.FP2PStartExtract(lNewProcessor,strFilepathString.getBytes(), "".getBytes());
				if (nStartExtract == 3) {
					logger.debug("need password!");
				}
				// create dir
				File dirFile = new File(strSrcPath + "/" + this.strCurrFileName.substring(0, length - 4));
				dirFile.mkdir();
				
				this.nCurrPage = 0;
				this.nCurrParaGraph = 0;
				int nPageCount = PDF2PDF.FP2PCountPage(lNewProcessor);
				for (int i = 0; i < nPageCount; ++i) {
					int nParagraph = PDF2PDF.FP2PCountParagraph(lNewProcessor, i);
					List<myParagraph> paragraphList = new ArrayList<myParagraph>();
					
					this.nCurrPage = i;
					logger.debug("CurrPage: " + this.nCurrPage);
					
					for (int j = 0; j < nParagraph; ++j) {

						this.nCurrParaGraph = j;
						logger.debug("CurrParaGraph: " + this.nCurrParaGraph);
						
						boolean bIsDepend = PDF2PDF.FP2PIsAllLineIsIndepend(lNewProcessor, i,j);
						if (bIsDepend) {
							List<myParagraph> subList = new ArrayList<myParagraph>();
							int nRowCount = PDF2PDF.FP2PCountIndependLineInParagraph(lNewProcessor, i, j);
							logger.debug("nRowCount: " + nRowCount);
							for (int k = 0; k < nRowCount; k++) {
								long lStrContent = PDF2PDF.FP2PGetIndependLineContent(lNewProcessor, i, j, k);
								logger.debug("PDF2PDF.FP2PGetIndependLineContent---End ");
								String strContent = PDF2PDF.FP2PGetContent(lStrContent);
								PDF2PDF.FP2PFreeContent(lStrContent);

								logger.debug("strContent: " + strContent);
								myParagraph dependParagraph = new myParagraph(k, 0, 1, strContent, null);
								subList.add(dependParagraph);
							}

							logger.debug("bIsDepend: " + "-----out");
							myParagraph paragraph = new myParagraph(j, 0,1, "", subList);
							paragraphList.add(paragraph);
						} else {
							long lParagraphContent = PDF2PDF.FP2PGetParagraphContent(lNewProcessor,i, j);
							String strContent = PDF2PDF.FP2PGetContent(lParagraphContent);
							PDF2PDF.FP2PFreeContent(lParagraphContent);
							myParagraph paragraph = new myParagraph(j, 1,0, strContent, null);
							paragraphList.add(paragraph);
						}
					} 
					logger.debug("generateXml");
					String xmlStrSrcPath = strSrcPath + "/" + this.strCurrFileName.substring(0,this.strCurrFileName.length() - 4) + "/" + i + ".xml";
					XmlGenerator generateXml = new XmlGenerator();
					generateXml.generateXmlByList(xmlStrSrcPath, paragraphList);
					logger.debug("generateXml End !!!");
				}

				PDF2PDF.FP2PCloseProcessor(lNewProcessor);
				PDF2PDF.FP2PDestroyModuleMgr(lMgr);
			}
        }
        logger.debug("generateXml End!!!********************");
	}

	@RequestMapping(value = "/recombine.do")
	public void recombine(HttpServletRequest request,
			HttpServletResponse response) {
		logger.debug("RecombinePDF Begin!!!********************");
		File file = new File(this.strSrcPath);
		File[] filelist = file.listFiles();
		for (File f : filelist){
        	//判断是否是pdf文件夹
        	if (f.isDirectory()) {
        		String strDir = f.getName();
        		
        		this.strCurrFileName = f.getName() + ".pdf";
        		logger.debug("CurrFile:" + this.strCurrFileName);
        		
        		long lMgr = PDF2PDF.FP2PCreateModuleMgr();
        		long lNewProcessor = PDF2PDF.FP2PNewProcessor();
        		String strFilepathString = strSrcPath + "/" + strDir + ".pdf";
        		PDF2PDF.FP2PStartExtract(lNewProcessor,strFilepathString.getBytes(), "".getBytes());

        		String strFilePath = strSrcPath + "/" + strDir;
        		File xmlFiles = new File(strFilePath);
        		String[] xmlList = xmlFiles.list();
        		
        		this.nCurrPage = 0;
        		
                for (int i = 0; i < xmlList.length; i++) {
                	
                	this.nCurrPage = i;
                	logger.debug("CurrPage:" + this.nCurrPage);
                	
        			File readfile = new File(strFilePath + "/" + i + ".xml");    				
    				String strXmlFileNameString = readfile.getName();
    				logger.debug("strXmlFileName: " + strXmlFileNameString);
    				XmlParse parse = new XmlParse();
    				parse.parserXml(strFilePath + "/" + strXmlFileNameString, lNewProcessor, i);
                }
                String strNewFileName = strFilePath + "/" + this.strCurrFileName.substring(0,this.strCurrFileName.length() - 4) + "-Re.pdf";
                PDF2PDF.FP2PSaveFile(lNewProcessor, strNewFileName.getBytes());
                
                PDF2PDF.FP2PCloseProcessor(lNewProcessor);
        		PDF2PDF.FP2PDestroyModuleMgr(lMgr);
        	}
        }
	}
	
	//删除文件夹下的子文件夹
	private void deleteSubDirectory(String strPath){
		if (!strPath.endsWith(File.separator)) {
			strPath = strPath + File.separator;
		}
		
		File dirFile = new File(strPath);
		
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			return;
		}
		
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				File[] xmlFiles = files[i].listFiles();
				for (int j = xmlFiles.length - 1; j >= 0; j--) {
					if (xmlFiles[j].isFile() && xmlFiles[j].exists()) {
						xmlFiles[j].delete();
					}
				}
				files[i].delete();
			}
		}
	}
}
